package ClientsAndHotels;

import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.io.IOException;

import ClientsAndHotels.types.DiedAgentData;

/**
 * 
 * Tu są wszystkie funkcje wspólne dla wszystkich agentów w systemie
 */
public abstract class BaseAgent extends Agent {

    private boolean registeredOnYellowPages = false;
    private boolean notifyAboutDie = false;
    private int type;

    /**
     * Rejestruje się na żółtych kartach
     * 
     * @param type
     *            typ agenta
     * @param name
     *            nazwa agenta
     */
    protected void registerOnYellowPages(String type, String name) {
        DFAgentDescription dfd = new DFAgentDescription();
        dfd.setName(getAID());
        ServiceDescription sd = new ServiceDescription();
        sd.setType(type);
        sd.setName(name);
        dfd.addServices(sd);
        try {
            DFService.register(this, dfd);
        } catch (FIPAException fe) {
            fe.printStackTrace();
        }
        registeredOnYellowPages = true;
    }

    protected void notifyGuiAboutDie(int type) {
        this.type = type;
        notifyAboutDie = true;
    }

    /**
     * Wpisywanie logu na standardowe wyjście
     * 
     * @param msg
     *            wiadomość
     * @param args
     *            parametry wiadomości
     */
    public void log(String msg, Object... args) {
        System.out.println(String.format("%s: %s", getLocalName(),
                String.format(msg, args)));
    }

    /**
     * "Pożegnaj się"
     */
    @Override
    protected void takeDown() {
        if (notifyAboutDie) {
            ACLMessage message = new ACLMessage(ACLMessage.INFORM);
            message.addReceiver(new AID("gui", false));
            message.setLanguage("JavaSerialization");
            message.setConversationId(GuiAgent.AGENT_DIED_CONVERSATION);
            try {
                message.setContentObject(new DiedAgentData(type, getLocalName()));
                send(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (registeredOnYellowPages) {
            try {
                DFService.deregister(this);
            } catch (FIPAException fe) {
                fe.printStackTrace();
            }
        }
        log("Kończę swoje działanie");
        super.takeDown();
    }

}
